import { defineStore } from 'pinia'
import { ref } from 'vue'
import { authApi } from '@/api/auth'
import { permissionApi } from '@/api/permissions'

interface User {
  id: number
  username: string
  email: string
  fullName?: string
  roles: Array<{
    id: number
    name: string
    description: string
  }>
}

interface MenuTreeItem {
  id: number
  name: string
  path?: string
  component?: string
  icon?: string
  children?: MenuTreeItem[]
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const permissions = ref<string[]>([])
  const userMenus = ref<MenuTreeItem[]>([])

  // 初始化认证状态
  const initAuth = async () => {    
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    
    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        user.value = JSON.parse(savedUser)
        
        // 加载权限
        await loadPermissions()
      } catch (error) {
        console.error('[AuthStore] 初始化失败:', error)
        logout()
      }
    } else {
      console.log('[AuthStore] 没有保存的认证信息')
    }
  }

  const login = async (credentials: { username: string; password: string }) => {
    try {
      const response = await authApi.login(credentials)
      token.value = response.data.token
      user.value = response.data.user
      
      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      // 获取用户权限
      await loadPermissions()
      
      return response
    } catch (error) {
      throw error
    }
  }

  const loadPermissions = async () => {
    try {
      const response = await permissionApi.getUserPermissions()
      permissions.value = response.data
    } catch (error) {
      console.error('加载权限失败:', error)
      permissions.value = []
    }
  }

  const setUser = (userData: User) => {
    user.value = userData
  }

  const setToken = (tokenValue: string) => {
    token.value = tokenValue
  }

  const setMenus = (menus: MenuTreeItem[]) => {
    userMenus.value = menus
  }

  const getMenus = () => {
    return userMenus.value
  }

  const logout = () => {
    token.value = null
    user.value = null
    permissions.value = []
    userMenus.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  const isAuthenticated = () => {
    return !!token.value
  }

  const hasRole = (roleName: string): boolean => {
    if (!user.value || !user.value.roles) {
      return false
    }
    return user.value.roles.some((role: any) => role.name === roleName)
  }

  return {
    token,
    user,
    permissions,
    userMenus,
    initAuth,
    login,
    logout,
    isAuthenticated,
    loadPermissions,
    setUser,
    setToken,
    setMenus,
    getMenus,
    hasRole
  }
})

